package com.lmx.project.controller;

import com.lmx.project.common.BaseResponse;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.common.ResultUtils;
import com.lmx.project.exception.BusinessException;
import com.lmx.project.model.dto.category.CategoryRequestUpdate;
import com.lmx.project.model.entity.Category;
import com.lmx.project.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lmx
 * 本类负责有关开设类别的增删改查
 */
@RestController
@RequestMapping("/categoty")
public class CategotyController {
    @Resource
    private CategoryService categoryService;

    /**
     * 获取所有的类别
     */

    @GetMapping()
    public BaseResponse<List<Category>> getAllCategory() {
        List<Category> list = categoryService.list();
        return ResultUtils.success(list);
    }

    /**
     * 添加竞赛小组的开设类别
     * Todo 需要管理员权限
     */
    @PostMapping()
    public BaseResponse<Long> AddCategory(String text) {
        if (!StringUtils.isNotBlank(text)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "类别不能为空");
        }
        Category category = new Category();
        category.setName(text);
        boolean save = categoryService.save(category);
        if (save) {
            return ResultUtils.success(category.getId());
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "添加竞赛小组的开设类别接口异常");
        }
    }


    /**
     * 修改竞赛小组的开设类别
     * Todo 需要管理员权限
     */
    @PutMapping()
    public BaseResponse<Long> AddCategory(@RequestBody CategoryRequestUpdate categoryRequestUpdate) {
        if (categoryRequestUpdate == null || categoryRequestUpdate.getId() == null || categoryRequestUpdate.getId() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能为空");
        }

       Long  id = categoryService.updateCategory(categoryRequestUpdate);
        if (id!=null) {
            return ResultUtils.success(id);
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "修改竞赛小组的开设类别异常");
        }
    }

    /**
     * 删除接口
     * Todo 需要管理员权限
     */
    @DeleteMapping()
    public BaseResponse<Boolean> DeleteCategory(Long id) {
        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能为空");
        }

        //        判断是否存在
        Category byId = categoryService.getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该类别不存在");
        }

//        进行删除
        boolean b = categoryService.removeById(id);
        return ResultUtils.success(b);
    }
}
